//
//  TaskManager.m
//  Task Views
//
//  Created by Chris Karr on 2/18/09.
//  Copyright 2009 Chris J. Karr. All rights reserved.
//

#import "TaskManager.h"
#import "AttributeValueFormatter.h"

@implementation TaskManager

- (id) init
{
	if (self = [super init])
		taskData = nil;
	
	return self;
}

@synthesize selectedAttributeType;

- (void) awakeFromNib
{
	NSArray * fileTasks = [NSKeyedUnarchiver unarchiveObjectWithFile:[self taskDataLocation]];

	[tasks addObjects:fileTasks];
	
	AttributeValueFormatter * formatter = [[AttributeValueFormatter alloc] init];
	[[valueColumn dataCell] setFormatter:formatter];
	
	[tasks addObserver:self forKeyPath:@"selection" options:0 context:NULL];
	
	[formatter release];
}

- (NSString *) taskDataLocation
{
	NSString * applicationSupportFolder = nil;
	FSRef foundRef;
	OSErr err = FSFindFolder (kUserDomain, kApplicationSupportFolderType, kCreateFolder, &foundRef);
			
	if (err != noErr) 
	{
		NSRunAlertPanel (NSLocalizedString (@"Alert", nil), NSLocalizedString (@"Can't find application support folder", nil), 
						 NSLocalizedString (@"Quit", nil), nil, nil);
		[[NSApplication sharedApplication] terminate:self];
	}
	else 
	{
		unsigned char path[1024];
		FSRefMakePath (&foundRef, path, sizeof(path));
		applicationSupportFolder = [NSString stringWithUTF8String:(char *) path];
		applicationSupportFolder = [applicationSupportFolder stringByAppendingPathComponent:@"Task Views"];
		
		if (![[NSFileManager defaultManager] fileExistsAtPath:applicationSupportFolder])
			[[NSFileManager defaultManager] createDirectoryAtPath:applicationSupportFolder attributes:[NSDictionary dictionary]];
	}
	
	return [applicationSupportFolder stringByAppendingPathComponent:@"Tasks.plist"];
}

- (IBAction) newTask:(id)sender
{
	NSMutableDictionary * task = [NSMutableDictionary dictionary];
	[task setValue:@"New Task" forKey:@"name"];
	[task setValue:@"Task Views" forKey:@"source"];
	[task setValue:[NSNumber numberWithBool:NO] forKey:@"Hide"];
	[task setValue:[NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]] forKey:@"id"];
	[tasks addObject:task];
	
	[[NSNotificationCenter defaultCenter] postNotificationName:@"refresh_fields" object:nil];
}

- (IBAction) removeTask:(id)sender
{
	NSArray * selectedTasks = [tasks selectedObjects];
	
	NSString * title = nil;
	NSString * message = nil;
	
	if ([selectedTasks count] == 1)
	{
		NSDictionary * selectedTask = [selectedTasks lastObject];
	
		title = [NSString stringWithFormat:@"Delete '%@'?", [selectedTask valueForKey:@"name"]];
		message = [NSString stringWithFormat:@"Are you sure that you wish to delete the task '%@'?", [selectedTask valueForKey:@"name"]];
	}
	else
	{
		title = [NSString stringWithFormat:@"Delete %d Tasks?", [selectedTasks count]];
		message = @"Are you sure that you wish to delete the selected tasks?";
	}
	
	if ([selectedTasks count] > 0)
	{
		if (NSAlertDefaultReturn == NSRunAlertPanel(title, message, @"Yes", @"No", nil))
				[tasks remove:sender];
	}
}

- (IBAction) editTask:(id)sender
{
	[editWindow makeKeyAndOrderFront:sender];
	[editWindow orderFrontRegardless];
}

- (IBAction) addAttribute:(id)sender
{
	[self willChangeValueForKey:@"currentTask"];
	NSMutableDictionary * selectedTask = [[tasks selectedObjects] lastObject];
	
	[selectedTask setValue:@"New Value" forKey:@"New Attribute"];

	[self didChangeValueForKey:@"currentTask"];
	
	for (NSDictionary * pair in [attributes arrangedObjects])
	{
		if ([[pair valueForKey:@"key"] isEqualToString:@"New Attribute"])
			[attributes setSelectedObjects:[NSArray arrayWithObject:pair]];
	}

	[self editAttribute:sender];
}

- (IBAction) removeAttribute:(id)sender
{	
	[attributes remove:sender];
}

- (IBAction) editAttribute:(id)sender
{	
	if (![editWindow isVisible])
		[editWindow makeKeyAndOrderFront:sender];

	NSMutableDictionary * selectedTask = [[tasks selectedObjects] lastObject];
	NSMutableDictionary * selectedAttribute = [[attributes selectedObjects] lastObject];
	
	NSObject * value = [selectedTask valueForKey:[selectedAttribute valueForKey:@"key"]];
	
	[self willChangeValueForKey:@"selectedAttributeType"];
	
	if ([value isKindOfClass:[NSNumber class]])
	{
		self.selectedAttributeType = @"Number";
		
		[textField setStringValue:[value description]];
		[numberField setStringValue:[value description]];
		[listField setString:[value description]];
		[dateField setDateValue:[NSDate date]];
	}
	else if ([value isKindOfClass:[NSDate class]])
	{
		self.selectedAttributeType = @"Date";

		[dateField setDateValue:((NSDate *) value)];
		[textField setStringValue:[value description]];
		[listField setString:[value description]];
		[numberField setStringValue:[value description]];
	}
	else if ([value isKindOfClass:[NSArray class]])
	{
		self.selectedAttributeType = @"List";

		NSMutableString * string = [NSMutableString string];
		
		for (id item in ((NSArray *) value))
		{
			if (![string isEqualToString:@""])
				[string appendString:@"\r"];
			
			[string appendString:[item description]];
		}
			
		[listField setString:string];
		[textField setStringValue:string];
		[numberField setStringValue:string];
		[dateField setDateValue:[NSDate date]];
	}
	else
	{
		self.selectedAttributeType = @"Text";

		if (value == nil)
			value = @"";
		
		[textField setStringValue:[value description]];
		[numberField setStringValue:[value description]];
		[listField setString:[value description]];
		[dateField setDateValue:[NSDate date]];
	}
	
	[self didChangeValueForKey:@"selectedAttributeType"];
	
	[NSApp beginSheet:attributePanel modalForWindow:editWindow modalDelegate:self didEndSelector:nil contextInfo:NULL];
}

- (IBAction) finishAttributeEdit:(id)sender
{	
	[self willChangeValueForKey:@"currentTask"];

	id value = nil;
	
	if ([self.selectedAttributeType isEqualToString:@"Date"])
		value = [dateField dateValue];
	else if ([self.selectedAttributeType isEqualToString:@"List"])
		value = [[listField string] componentsSeparatedByString:@"\r"];
	else if ([self.selectedAttributeType isEqualToString:@"Number"])
	{
		NSScanner * scanner = [NSScanner scannerWithString:[numberField stringValue]];
		
		double d = 0;
		if ([scanner scanDouble:&d])
			value = [NSNumber numberWithDouble:d];
	}
	else
		value = [textField stringValue];
	
	if (value == nil)
		value = @"";
	
	NSMutableDictionary * selectedTask = [[tasks selectedObjects] lastObject];
	NSMutableDictionary * selectedAttribute = [[attributes selectedObjects] lastObject];

	[selectedTask setValue:value forKey:[selectedAttribute valueForKey:@"key"]];

	[self didChangeValueForKey:@"currentTask"];

	[[NSNotificationCenter defaultCenter] postNotificationName:@"refresh_fields" object:nil];

	[NSApp endSheet:attributePanel];
	[attributePanel orderOut:self];
}

- (NSMutableDictionary *) currentTask
{
	if ([[tasks selectedObjects] count] > 0)
		return [[tasks selectedObjects] lastObject];
	
	return nil;
}

- (void) setCurrentTask:(NSDictionary *) task
{
	NSMutableDictionary * current = [self currentTask];
	
	[current setDictionary:task];
}

- (void) observeValueForKeyPath: (NSString *) keyPath ofObject:(id) object change:(NSDictionary *) change context:(void *) context
{
	[self willChangeValueForKey:@"currentTask"];
	
	[self didChangeValueForKey:@"currentTask"];
}

- (void) updatePriorities:(NSArray *) taskArray priority:(NSString *) priority
{
	for (NSMutableDictionary * task in taskArray)
		[task setValue:priority forKey:@"task_priority"];
}

- (IBAction) setVeryLowPriority:(id)sender
{
	[self updatePriorities:[tasks selectedObjects] priority:@"Very Low"];
}

- (IBAction) setLowPriority:(id)sender
{
	[self updatePriorities:[tasks selectedObjects] priority:@"Low"];
}

- (IBAction) setNormalPriority:(id)sender
{
	[self updatePriorities:[tasks selectedObjects] priority:@"Normal"];
}

- (IBAction) setHighPriority:(id)sender;
{
	[self updatePriorities:[tasks selectedObjects] priority:@"High"];
}

- (IBAction) setVeryHighPriority:(id)sender;
{
	[self updatePriorities:[tasks selectedObjects] priority:@"Very High"];
}


@end
